package com.xianyun.book.gatewayimpl.handle;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.Assert;
import com.xianyun.book.common.core.handle.HandleChain;
import com.xianyun.book.common.core.handle.HandleChainFactory;
import com.xianyun.book.common.core.handle.HandleParam;
import com.xianyun.book.convertor.OrderConvertor;
import com.xianyun.book.domain.book.Book;
import com.xianyun.book.domain.order.Order;
import com.xianyun.book.gatewayimpl.database.OrderMapper;
import com.xianyun.book.gatewayimpl.handle.strategy.BookDatabaseSingleHandle;
import com.xianyun.book.gatewayimpl.handle.strategy.BookLibrarySingleHandle;
import com.xianyun.book.gatewayimpl.handle.strategy.DouBanBookSingleHandle;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author macos-zyj
 */
@CatchAndLog
@Slf4j
@Component
public class IsbnQueryGatewayHandle {
    /**
     *必须保证对应的查询顺序 优先本数据库 其次再查询豆瓣和book library 最后用网络Api兜底
     */
    private final HandleChain<Book,String> handleChain = HandleChainFactory.buildHandleChain(
            BookDatabaseSingleHandle.class,
            DouBanBookSingleHandle.class,
            BookLibrarySingleHandle.class
    );

    @Resource
    private OrderMapper orderMapper;

    public Book execute(@NonNull String isbn){
        HandleParam<String> handleParam = new HandleParam<>();
        handleParam.setHandleData(isbn);
        Book queryBook = handleChain.doHandle(handleParam);
        Assert.notNull(queryBook,"该ISBN对应的书籍不存在");
        List<Order> orderList = OrderConvertor.toDataTranslateList(orderMapper.selectOrdersByIsbn(isbn));
        queryBook.setBookOrders(orderList);
        return queryBook;
    }


}
